// pages/indexSearchShop/indexSearchShop.js
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let user_js = require("../../utils/user.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    loactionCityInfo: null,
    contentStatus: -1, //1有数据
    isSearching: false,
    keyWord: '',
    noShopUrl: url_js.imgUrl + "no_shop.png",
    searchingStatus: -1, //0:搜索没有内容 1有内容
    unSearchStatus: -1, //0:无数据，1有数据
    myZtdInfo: null,
    noLocationUrl: url_js.imgUrl + "no_location.png",
    shopNearbyList: [],
    nearbyPageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    searchPageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    searchResultList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function(options) {
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo,
      myZtdInfo: tempUserInfo.ztd
    });
    //获取用户定位
    this.getUserLocation();
  },

  //点击省市信息
  onCityName: function() {
    this.getUserLocation(true);
  },

  //获取用户定位
  getUserLocation: function(openInlineMap) {
    //地图加载
    common_js.showLoading();
    wx.getSetting({
      complete: res => {
        common_js.hideLoading();
        if (common_js.containsKeyString(res.errMsg, "ok")) {
          if (!res.authSetting['scope.userLocation']) {
            //2.提前授权
            common_js.showLoading();
            wx.authorize({
              scope: 'scope.userLocation',
              complete: res => {
                common_js.hideLoading();
                if (common_js.containsKeyString(res.errMsg, "ok")) {
                  //3.获取经纬度
                  common_js.showLoading();
                  wx.getLocation({
                    type: 'wgs84',
                    complete: res => {
                      common_js.hideLoading();
                      if (common_js.containsKeyString(res.errMsg, "ok")) {
                        if (openInlineMap) {
                          this.openWechatLocation(res, openInlineMap);
                        } else {
                          this.requestToGetLocationSaveUrl(res);
                        }
                      } else {
                        common_js.showToast("获取当前位置失败，请重试!")
                      }
                    }
                  });
                } else {
                  //拒绝授权
                  this.handleMapFailAuthDeny(res);
                }
              },
            })
          } else {
            //3.获取经纬度
            common_js.showLoading();
            wx.getLocation({
              type: 'wgs84',
              complete: res => {
                common_js.hideLoading();
                if (common_js.containsKeyString(res.errMsg, "ok")) {
                  if (openInlineMap) {
                    this.openWechatLocation(res, openInlineMap);
                  } else {
                    this.requestToGetLocationSaveUrl(res);
                  }
                } else {
                  common_js.showToast("获取当前位置失败，请重试!")
                }
              }
            });
          }
        } else {
          common_js.showToast("获取当前设置失败，请重试!");
        }
      }
    });
  },

  //打开微信内置地图
  openWechatLocation: function(res, openInlineMap) {
    const latitude = res.latitude;
    const longitude = res.longitude;
    //2.打开地图选择位置
    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: res => {
        //1.设置参数
        this.requestToGetLocationSaveUrl(res);
      },
      fail: res => {
        var canceled = res.errMsg.indexOf("cancel") != -1;
        if (canceled) {
          common_js.showModal("亲，我们未获得您的位置，请重新选择", null, true, null, null, () => {
            this.getUserLocation(openInlineMap);
          });
        }
      }
    });
  },

  //处理拒绝地图授权
  handleMapFailAuthDeny: function(res) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common_js.showModal("亲，我们未获得您的位置授权，即将打开设置", null, true, null, null, () => {
      wx.openSetting({
        success: res => {
          var isOpenUserLocation = res.authSetting['scope.userLocation'];
          // 选择自提点
          if (isOpenUserLocation) {
            this.getUserLocation();
          }
        }
      })
    })
  },

  //根据当前的经纬度获取locationSaveUrl
  requestToGetLocationSaveUrl: function(location) {
    //1.我的自提点
    let data = {
      code: user_js.getCode(),
      lat: location.latitude,
      lon: location.longitude
    }
    api.wxRequest(url_js.locationSaveUrl, data).then(res => {
      this.handleLocationSaveData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的经纬度数据
  handleLocationSaveData: function(res) {
    if (!res.result) {
      common_js.showToast("经纬度获取失败");
      return;
    }
    this.setData({
      contentStatus: 1,
      loactionCityInfo: res.result
    });
    //根据当前经纬度去请求数据
    this.getRemoteDatas(res.result);
  },

  //网络请求获取数据
  getRemoteDatas: function() {
    //2.查询附近店铺信息
    this.requestToGetShopList(this.data.nearbyPageInfo.curPage, this.data.nearbyPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, '', true);
  },

  //跟新我的自提点信息,用于选择完回来更新
  updateMyZtdInfo: function(res) {
    this.setData({
      myZtdInfo: res
    });
  },

  //请求获取附近的自提点
  requestToGetShopList: function(currPage, pageSize, lat, lon, shopName, pullDownRefresh) {
    let data = {
      currPage: currPage,
      lat: lat,
      lon: lon,
      pageSize: pageSize,
      shopName: shopName
    };
    api.wxRequest(url_js.shopListUrl, data).then(res => {
      this.hanldeNearbyShopsData(res, currPage, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理返回的附近的自提点列表
  hanldeNearbyShopsData: function(res, currPage, pullDownRefresh) {
    if (this.data.isSearching) {
      //设置数据
      var tmpShopList = this.data.searchResultList;
      if (pullDownRefresh) {
        tmpShopList = [];
      }
      //pageInfo
      var tmpPageInfo = this.data.searchPageInfo;
      if (res.page.pages <= currPage) {
        tmpPageInfo.noMore = true;
      } else {
        tmpPageInfo.curPage++;
      }
      //list
      if (res.result.length > 0) {
        tmpShopList = tmpShopList.concat(res.result);
        this.setData({
          searchingStatus: 1,
          searchPageInfo: tmpPageInfo,
          searchResultList: tmpShopList
        });
      } else {
        this.setData({
          searchingStatus: 0,
          searchPageInfo: tmpPageInfo
        });
      }
    } else {
      //设置数据
      var tmpShopList = this.data.shopNearbyList;
      if (pullDownRefresh) {
        tmpShopList = [];
      }
      //pageInfo
      var tmpPageInfo = this.data.nearbyPageInfo;
      if (res.page.pages <= currPage) {
        tmpPageInfo.noMore = true;
      } else {
        tmpPageInfo.curPage++;
      }
      //list
      if (res.result.length > 0) {
        tmpShopList = tmpShopList.concat(res.result);
        this.setData({
          nearbyPageInfo: tmpPageInfo,
          shopNearbyList: tmpShopList,
          unSearchStatus: 1
        });
      }
    }
  },

  //添加自提点--type:1附近  2.搜索结果 index为type对应的数组的index
  requestToAddShop: function(cityId, shopId, type, index) {
    let data = {
      cityId: cityId,
      code: user_js.getCode(),
      shopId: shopId
    };
    api.wxRequest(url_js.shopAddShopUrl, data).then(res => {
      this.handleAddShopData(res, type, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加自提点返回的自提点数据
  handleAddShopData: function(res, type, index) {
    common_js.showToast("添加成功");
    if (type == 1) {
      var item = this.data.shopNearbyList[index];
      item.hasJoin = true;
      this.setData({
        shopNearbyList: this.data.shopNearbyList
      });
    } else {
      var item = this.data.searchResultList[index];
      item.hasJoin = true;
      this.setData({
        searchResultList: this.data.searchResultList
      });
    }
  },

  //搜索附近的门店
  bindSearchInput: function(e) {
    var tmpKeyWord = e.detail.value;
    if (tmpKeyWord.length > 0) {
      this.setData({
        isSearching: true,
        searchingStatus: -1,
        keyWord: tmpKeyWord,
      });
    } else {
      this.setData({
        isSearching: false
      })
    }
  },

  //搜索结束
  onSearchDone: function(res) {
    // set data
    if (!this.data.keyWord) return;
    // reset page 
    var tmpPageInfo = this.data.searchPageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      searchPageInfo: tmpPageInfo
    });

    //根据关键词去搜索
    this.requestToGetShopList(this.data.searchPageInfo.curPage, this.data.searchPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, this.data.keyWord, true);
  },

  //重新定位
  onRelocation: function() {
    this.getUserLocation();
  },

  //我的自提点
  onMyZtd: function() {
    var item = common_js.jsonStringify(this.data.loactionCityInfo);
    wx.navigateTo({
      url: '../indexMyZtPosition/indexMyZtPosition?locationInfo=' + item
    })
  },

  //添加自提点
  onAddNearbyZtd: function(e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexSearchShopAdd);

    var index = e.currentTarget.dataset.index;
    //添加自提点
    var item = this.data.shopNearbyList[index];
    this.requestToAddShop(this.data.loactionCityInfo.cityId, item.id, 1, index);
  },

  //搜索中添加自提点
  onSearchAddNearbyZtd: function(e) {
    var index = e.currentTarget.dataset.index;
    //添加自提点
    var item = this.data.searchResultList[index];
    this.requestToAddShop(this.data.loactionCityInfo.cityId, item.id, 2, index);
  },

  //切换自提点
  onToggleZtd: function(e) {
    //跳转我的自提点列表
    var item = common_js.jsonStringify(this.data.loactionCityInfo);
    wx.navigateTo({
      url: '../indexMyZtPosition/indexMyZtPosition?locationInfo=' + item
    })
  },

  //联系店长
  contactDz: function() {
    if (!this.data.myZtdInfo.mobile) {
      common_js.showToast("电话不存在！");
      return
    }
    //打电话
    wx.makePhoneCall({
      phoneNumber: this.data.myZtdInfo.mobile
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (!this.data.isSearching) {
      if (this.data.unSearchStatus == 1) {
        if (this.data.nearbyPageInfo.noMore) return;
        //请求数据
        this.requestToGetShopList(this.data.nearbyPageInfo.curPage, this.data.nearbyPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, '');
      }
    } else {
      //搜索中的状态
      if (this.data.searchingStatus == 1) {
        if (this.data.searchPageInfo.noMore) return;
        //请求数据
        this.requestToGetShopList(this.data.searchPageInfo.curPage, this.data.searchPageInfo.pageSize, this.data.loactionCityInfo.lat, this.data.loactionCityInfo.lon, this.data.keyWord);
      }
    }
  }
})